package com.hua.yuan.manager.user.business.dao.impl;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.hua.yuan.common.https.OkHttpModule;
import com.hua.yuan.manager.user.UserManagerModule;
import com.hua.yuan.manager.user.business.api.IUserUpdateApi;
import com.hua.yuan.manager.user.business.callback.IUserCallback;
import com.hua.yuan.manager.user.business.dao.IRegisterDao;
import com.hua.yuan.provider.user.IUserProvider;
import com.hua.yuan.provider.user.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @Author: richsjeson.
 * @Description: TODO()
 * @Date:Created in 2019/1/2 10:22 PM.
 * @Modified By:
 */
public class RegisterDaoImpl implements IRegisterDao {

    private Disposable mDisposable;

    private Retrofit mRetrofit;

    public RegisterDaoImpl(){
        mRetrofit = OkHttpModule.getInstance().getRetrofit();
    }


    @Override
    public void registerUser(@NonNull final Map pMap, @NonNull final IUserProvider pProvider, final IUserCallback pCallback) {

        if (mDisposable != null) {
            if (!mDisposable.isDisposed()) {
                mDisposable.dispose();
            }
        }

        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> pEmitter) {
                //无论如何都要刷新Token
                IUserUpdateApi updateApi = mRetrofit.create(IUserUpdateApi.class);
                Call<String> call = updateApi.register(pMap);
                Response<String> response;
                try {
                    response = call.execute();
                    String result = response.body();
                    //如果返回值为空
                    if (TextUtils.isEmpty(result)) {
                        pEmitter.onError(new NullPointerException());
                    }
                    parser(result,pEmitter);
                } catch (IOException e) {
                    e.printStackTrace();
                    pEmitter.onError(e);
                }
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(final Disposable pDisposable) {
                        mDisposable = pDisposable;
                    }

                    @Override
                    public void onNext(final Boolean pIsSuccess) {
                        if (pIsSuccess) {
                            //执行操作
                            updateUser(pMap,pProvider,pCallback);
                        }else{
                            pCallback.onResult(null);
                        }
                    }

                    @Override
                    public void onError(final Throwable e){

                        mDisposable.dispose();
                        pCallback.onError(e);
                    }

                    @Override
                    public void onComplete() {
                        mDisposable.dispose();
                    }
                });
    }



    /**
     * 更新用户接口信息
     * @param pMap 需要修改的对象
     * @param pProvider  对外提供的Provider类
     * @param pCallback
     */
    private void updateUser(final Map pMap, @NonNull final IUserProvider pProvider,final IUserCallback pCallback) {

        User userInfo =new User();

        String mobile= (String) pMap.get(UserManagerModule.MOBILE);
        String password= (String) pMap.get(UserManagerModule.PASSWORD);

        if(!TextUtils.isEmpty(mobile)){
            userInfo.setMobilePhone(mobile);
            userInfo.setUserName(mobile);
        }
        if(!TextUtils.isEmpty(password)){
            pProvider.setPassword(password);
        }
        pProvider.setUserInfo(userInfo);
        pCallback.onResult(userInfo);
    }

    /**
     * 解析操作
     * @param mResult
     * @param pEmitter
     */
    private void parser(String mResult,@NonNull ObservableEmitter pEmitter) {
        try {
            JSONObject resultJson = new JSONObject(mResult);
            pEmitter.onNext(resultJson.optInt(UserManagerModule.ERROR_NO)==0?true:false);
            pEmitter.onComplete();
        } catch (JSONException e) {
            e.printStackTrace();
            pEmitter.onError(e);
        }
    }
}
